package com.topdt.jbpm.web.servlet.action;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jbpm.api.model.ActivityCoordinates;

import com.thx.common.util.ThreadLocalContext;
import com.topdt.jbpm.Constants;
import com.topdt.jbpm.form.FormUI;
import com.topdt.jbpm.identity.Department;
import com.topdt.jbpm.identity.IdentityService;
import com.topdt.jbpm.identity.User;
import com.topdt.jbpm.model.HistTodo;
import com.topdt.jbpm.model.Todo;
import com.topdt.jbpm.model.Work;
import com.topdt.jbpm.model.WorkOpinion;
import com.topdt.jbpm.service.JbpmService;
import com.topdt.jbpm.web.servlet.JbpmServlet;
import com.topdt.jbpm.web.servlet.view.HistTodoView;
import com.topdt.jbpm.web.servlet.view.HistTodoViewComparator;

/**
 * 工作相关（从JbpmServlet中迁移过来）
 *
 * @author balancejia
 *
 */
public class WorkAction extends JbpmBaseAction {

  public WorkAction(JbpmServlet servlet) {
    super(servlet);
  }

  /**
   * 获取表单 从工作列表中获取表单
   *
   * @param request
   * @param response
   * @throws Exception
   */
  public void getWorkByWorkId(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    String workId = request.getParameter(Constants.WORKID_KEY);
    FormUI ui = servlet.getJbpmService().assembleForm(workId);
    ui.response(request, response);
  }

  public void getWorkByTodoId(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    String todoId = request.getParameter("todoId");
    Todo todo=this.jbpmService.getTodoById(todoId);
    FormUI ui = servlet.getJbpmService().assembleForm(todo.getWorkId());
    ui.response(request, response);
  }

  public void getWorkByWorkIdM(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    String workId = request.getParameter(Constants.WORKID_KEY);
    FormUI ui = servlet.getJbpmService().assembleForm(workId);
    ui.response(request, response);
  }

  public void getWorkByTodoIdM(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    String todoId = request.getParameter("todoId");
    Todo todo=this.jbpmService.getTodoById(todoId);
    FormUI ui = servlet.getJbpmService().assembleForm(todo.getWorkId());
    ui.response(request, response);
  }

  /**
   * 待办列表
   *
   * @param request
   * @param response
   * @throws Exception
   */
  public void todoList(HttpServletRequest request, HttpServletResponse response) throws Exception {
    User user = (User) ThreadLocalContext.get(Constants.USER_KEY);
    String starter = user.getId();
    List<Todo> todoList = getJbpmService().findReadyTodo(starter);
    responseJson(response, todoList);
  }

  /**
   * 列出起草的工作
   */
  public void listDraftWork(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    User user = (User) ThreadLocalContext.get(Constants.USER_KEY);
    String starter = user.getId();
    String state = "起草";
    List<Work> workList = getJbpmService().findWork(starter, state);
    responseJson(response, workList);
  }

  /**
   * 保存表单
   *
   * @param request
   * @param response
   * @throws Exception
   */
  public void saveWork(HttpServletRequest request, HttpServletResponse response) throws Exception {

    Map<String, String[]> parameter = request.getParameterMap();
    String workId = request.getParameter(Constants.WORKID_KEY);
    String todoId = request.getParameter("todoId");
    logger.debug(workId);

    getJbpmService().saveForm(workId, parameter, todoId);
    responseJson(response, "保存成功！");
  }

  /**
   * 删除工作
   */
  public void deleteWork(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String workId = request.getParameter("workId");
    User user = (User) ThreadLocalContext.get(Constants.USER_KEY);
    String userId = user.getId();
    String message = "";
    try {
      message = getJbpmService().deleteWork(workId, userId);
    } catch (Exception e) {
      message = "删除异常！";
      e.printStackTrace();
    }
    responseJson(response, message);
  }

  /**
   * 获取表单预览
   *
   * @param request
   * @param response
   * @throws Exception
   */
  public void getWorkViewByWorkId(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    String workId = request.getParameter(Constants.WORKID_KEY);
    boolean isPrint = false;
    if (request.getParameter("isPrint") != null)
      isPrint = Boolean.valueOf(request.getParameter("isPrint"));
    FormUI ui = getJbpmService().getWorkFormView(workId, isPrint);
    ui.response(request, response);
  }

  /**
   * 打印流程图片
   *
   * @param request
   * @param response
   * @throws Exception
   */
  public void printImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String workId = request.getParameter("workId");
    InputStream is = getJbpmService().getFlowImageIs(workId);
    byte[] pic = new byte[1024];
    int len = -1;
    while ((len = is.read(pic, 0, 1024)) != -1) {
      response.getOutputStream().write(pic, 0, len);
    }
  }

  /**
   * 获得当前的活跃环节
   *
   */
  public void getActivityNate(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    String workId = request.getParameter("workId");
    List<ActivityCoordinates> acs = getJbpmService().getActivityCoordinates(workId);
    responseJson(response, acs);
  }

  /**
   * 查找流转日志
   */
  public void findWorkRecord(HttpServletRequest request, HttpServletResponse response) {
    List<HistTodoView> listView = new ArrayList<HistTodoView>();
    try {
      String workId = request.getParameter("workId");
      IdentityService idServiceLocal = getIdService();
      JbpmService jbpmServiceLocal = getJbpmService();
      // 历史待办
      List<HistTodo> listHistTodo = jbpmServiceLocal.findWorkRecordFromHistTodo(workId);
      // 待办
      List<Todo> listTodo = jbpmServiceLocal.findWorkRecordFromTodo(workId);
      if (listHistTodo != null && listHistTodo.size() > 0) {
        for (int i = 0; i < listHistTodo.size(); i++) {
          HistTodoView histTodoView = new HistTodoView();
          histTodoView.setActivityName(listHistTodo.get(i).getActivityName());
          if (listHistTodo.get(i).getDestActivityName() == null
              || "".equals(listHistTodo.get(i).getDestActivityName())) {
            histTodoView.setDestActivityName("");
          } else {
            histTodoView.setDestActivityName(listHistTodo.get(i).getDestActivityName());
          }
          histTodoView.setArriveTime(listHistTodo.get(i).getArriveTime());
          histTodoView.setFinishTime(listHistTodo.get(i).getFinishTime());
          User user = idServiceLocal.getUserByUserId(listHistTodo.get(i).getToUser());
          Department department = idServiceLocal.getMajorDepOfUser(user.getId());
          if (department.getName() == null || "".equals(department.getName())) {
            histTodoView.setDepName("");
          } else {
            histTodoView.setDepName(department.getName());
          }
          histTodoView.setState(listHistTodo.get(i).getState());
          histTodoView.setUserName(user.getName());
          histTodoView.setBatch((listHistTodo.get(i).getBatch()));
          // 设置意见
          List<WorkOpinion> opinions =
              jbpmServiceLocal
                  .findOpinionByWorkIdAndTodoId(workId, listHistTodo.get(i).getTodoId());
          if (opinions != null && opinions.size() > 0) {
            histTodoView.setOpinion(opinions.get(0).getOpinionContent());
          } else {
            histTodoView.setOpinion("");
          }

          listView.add(histTodoView);
        }
      }
      if (listTodo != null && listTodo.size() > 0) {
        for (Todo histTodo : listTodo) {
          HistTodoView histTodoView = new HistTodoView();
          histTodoView.setActivityName(histTodo.getActivityName());
          histTodoView.setArriveTime(histTodo.getArriveTime());
          if (histTodo.getDestActivityName() == null || "".equals(histTodo.getDestActivityName())) {
            histTodoView.setDestActivityName("");
          } else {
            histTodoView.setDestActivityName(histTodo.getDestActivityName());
          }
          User user = idServiceLocal.getUserByUserId(histTodo.getToUserId());
          Department department = idServiceLocal.getMajorDepOfUser(user.getId());
          if (department.getName() == null || "".equals(department.getName())) {
            histTodoView.setDepName("");
          } else {
            histTodoView.setDepName(department.getName());
          }
          histTodoView.setState(histTodo.getState());
          histTodoView.setUserName(user.getName());
          histTodoView.setBatch(histTodo.getBatch());
          // 设置意见
          List<WorkOpinion> opinions =
              jbpmServiceLocal.findOpinionByWorkIdAndTodoId(workId, histTodo.getTodoId());
          if (opinions != null && opinions.size() > 0) {
            histTodoView.setOpinion(opinions.get(0).getOpinionContent());
          } else {
            histTodoView.setOpinion("");
          }

          listView.add(histTodoView);
        }
      }
      Collections.sort(listView, new HistTodoViewComparator());
      responseJson(response, listView);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
